<?php

namespace App\Admin\Controllers;

use App\Areas;
use App\Roles;
use App\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Http\Request;

class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('用户列表')
            ->description('description')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('Detail')
            ->description('description')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('编辑用户')
            ->description('description')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新建用户')
            ->description('description')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);

        $grid->id('Id');
        $grid->name('姓名');
        $grid->company('公司');
        $grid->nickname('登陆码');
        $grid->password('密码');
        $grid->column('area.name', '所属区域');
        $grid->column('role.name', '角色身份');
        $grid->column('parent_id', '所属上级公司');
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User);

        $form->text('name', '姓名')->rules(['required']);
        $form->text('company', '公司')->rules(['required']);
        $form->text('nickname', '登陆码')->rules(['required']);
        $form->password('password', '密码')->rules(['required']);
        $form->select('area_id', '所属区域')->options(Areas::all()->pluck('name', 'id'))->rules(['required']);
        $form->distpicker('role_id', '角色选择');
        $form->saved(function (Form $form) {
           $user = User::find($form->model()->id);
           $user->parent_id = $form->input('pid');
           $user->save();
        });
        return $form;
    }

}
